﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Applee.FractCommon;
using System.IO;
using System.Xml;
using System.Collections;
using System.Windows.Forms;
using Applee.FractManager;

namespace Applee.FractManager
{
    class FractConf : IFile
    {
        #region IFile 成员
        private string mText = null;
        public string Text
        {
            get
            {
                return mText;
            }
            set
            {
                mText = value;
            }
        }

        private static FractConf mInstance = new FractConf();
        public static FractConf Instance
        {
            get { return mInstance; }
        }

        public FractConf()
        {
            string strPath = Application.StartupPath;
            strPath = Path.Combine(strPath, "data");
            strPath = Path.Combine(strPath, ConstantString.g_conf_name);
            Read(strPath);
        }

        public void Read(string strPath)
        {
            if (!File.Exists(strPath))
                throw new FileNotFoundException(strPath);
   
            mText = File.ReadAllText(strPath);
        }

        public void Save(string strPath, string strText)
        {
            if (File.Exists(strPath))
                File.Delete(strPath);
            File.WriteAllText(strPath, strText);
        }

        #endregion

        public string GetNamedAttribute(string strFromName, string strDestName)
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.LoadXml(Text);

            XmlElement xmlChild = xmlDoc.SelectSingleNode(string.Format("//fract[@name=\'{0}\']", strFromName)) as XmlElement;
            if (xmlChild == null)
                return "";

            if (xmlChild.HasAttribute(strDestName))
                return xmlChild.GetAttribute(strDestName);

            return "";
        }

        public string[] GetNames()
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.LoadXml(Text);

            XmlNode xmlRoot = xmlDoc.SelectSingleNode("fracts");
            XmlNodeList xmlChildNodes = xmlRoot.ChildNodes;

            List<string> strNames = new List<string>();
            IEnumerator enumer = xmlChildNodes.GetEnumerator();
            while (enumer.MoveNext())
            {
                XmlElement xmlChild = enumer.Current as XmlElement;
                string strName = xmlChild.GetAttribute("name");
                strNames.Add(strName);
            }

            return strNames.ToArray();
        }

        public string GetClass(string strName)
        {
            return GetNamedAttribute(strName, "class");
        }

        public string GetPath(string strName)
        {
            return GetNamedAttribute(strName, "path");
        }
    }
}
